#!/bin/ruby

#########################
# iTunes Convert to M3U #
#########################
# Author:
# ------
# Sam Dekeyser
# 
# Usage:
# ------
# change the settings below to match your configuration
# create a directory to store your M3U files, make sure write permissions are allright.
#
# run the file:
#   ruby convert.rb
#
# Use mass_m3u.php to import the files into Ampache
#
# MIT License
#
#########################

require 'itunes/library'
require 'm3uzi'

###
# Settings
# Important: don't forget to add trailing slashes to the directories!
###
itunes_xml  = "path to itunes xml file"
itunes_lib  = "path to itunes music directory"
dest_dir    = "path to M3U destination directory"
# end of settings

print "Loading iTunes Library...\n"
library = ITunes::Library.load(itunes_xml)

print "#{library.playlists.count} playlists found in your library.\n"

print "Initiating conversion to M3U files...\n"
m3u = M3Uzi.new

library.playlists.each do |playlist|
  m3u = M3Uzi.new
    
  playlist.tracks.each do |track|
    m3u.add_file do |file|
      # Remove leading file://localhost from file path
      file.path     = CGI::unescape(track["Location"].gsub("file://localhost", ""))
      #file.duration = track["Total Time"]
      file.description = track["Name"]
    end
  end
  
  # Also replace unwanted characters for filenames with spaces
  m3u.write("#{dest_dir}#{playlist.name.tr("/`'", " ")}.m3u")
  print "[OK] #{playlist.name}\n"
end

print "Finished.\n"
